$(window).load(function() {
	initTopButton();
});

function addTags(post, tags) {
	$.post(window.updateUrl, 
		{ action: 'addTags', tags: tags, post: post }, 
		function(data) {
			$('.post-tags').replaceWith(data);
		}
	);
}

function updatePostRating(post, rating) {
	$.post(window.updateUrl, 
		{ action: 'setRating', rating: rating, post: post }, 
		function(data) {
			var w = data*24;
			$('#selRating .current-rating').css('width', w+'px');
		}
	);
}

function updatePostStatus(post, status) {
	$.post(window.updateUrl, 
		{ action: 'setStatus', status: status, post: post }, 
		function(data) {
			// success
		}
	);
}

function decorateList(list) {
	$(list).children(':first-child').addClass('first');
	$(list).children(':last-child').addClass('last');
}

function setLocation(url) {
	window.location.href = url;
}

function initTree(tree) {
	$.each($(tree + ' li'), function() {
		var self = $(this);
		if (self.has('ul').length) {
			self.toggle = function() {
				var ul = $(this).children('ul');
				if (ul.is(':visible')) {
					$(this).removeClass('expanded').addClass('collapsed');
					ul.hide();
				} else {
					$(this).addClass('expanded').removeClass('collapsed');
					ul.show();
				}
			};
			
			var icon = $('<div class="icon"></div>');
			icon.click(function () { self.toggle(); });
			self.prepend(icon);
			self.addClass('expanded').removeClass('collapsed');
		}
	});
}

function initSlider(options) {
	$('#'+options.id).slider({
		range: true,
		values: [ options.from, options.to ],
		min: options.min,
		max: options.max,
		step: options.step,
		change: function( event, ui ) {
			var tplUrl = unescape(options.tplUrl);
			var url = tplUrl.replace('#from', ui.values[0]).replace('#to', ui.values[1]);
			setLocation(url);
		},
		slide: function( event, ui ) {
			$( "#from" ).text(ui.values[0]);
			$( "#to" ).text(ui.values[1]);
		}
	});
}

function initLayer(layer) {
	$(layer+' input').on('change', function (e) {
		setLocation(this.value);
	});
}

function initTopButton() {
    $("#back-top").hide();

    // fade in #back-top
    $(function () {
        $(window).scroll(function () {
            if ($(this).scrollTop() > 100) {
                $('#back-top').fadeIn();
            } else {
                $('#back-top').fadeOut();
            }
        });

        // scroll on click
        $('#back-top a').click(function () {
            $('body,html').animate({
                    scrollTop: 0
                }, 800);
            return false;
        });
    });
}
